package com.ly.judge.callback;


import cn.hutool.core.util.StrUtil;
import com.github.dockerjava.api.model.Frame;
import com.github.dockerjava.api.model.StreamType;
import com.github.dockerjava.core.command.ExecStartResultCallback;
import com.ly.common.core.enums.CodeRunStatus;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

@Getter
@Setter
@Slf4j
public class DockerStartResultCallback extends ExecStartResultCallback {

    private CodeRunStatus codeRunStatus;  //记录执行成功还是失败

    private String errorMessage;

    private String message;

    //指令执行的输出,正确or错误,通过网络传输进去,onNext进行相应的处理
    @Override
    public void onNext(Frame frame) {
        // 获取数据帧的流类型(STDOUT/STDERR)
        StreamType streamType = frame.getStreamType();

        // 处理标准错误流
        if (StreamType.STDERR.equals(streamType)) {
            // 累积错误信息
            if (StrUtil.isEmpty(errorMessage)) {
                errorMessage = new String(frame.getPayload());
            } else {
                errorMessage = errorMessage + new String(frame.getPayload());
            }
            // 标记执行状态为失败
            codeRunStatus = CodeRunStatus.FAILED;
        }
        // 处理标准输出流
        else {
            String msgTmp = new String(frame.getPayload());
            if (StrUtil.isNotEmpty(msgTmp)) {
                // 保存输出信息
                message = new String(frame.getPayload());
            }
            // 标记执行状态为成功
            codeRunStatus = CodeRunStatus.SUCCEED;
        }

        // 调用父类处理逻辑
        super.onNext(frame);
    }
}
